// https://www.lintcode.cn/problem/minimum-adjustment-cost/description

class Solution {
public:
    /*
     * @param A: An integer array
     * @param target: An integer
     * @return: An integer
     */
     
    // [i][k] 表示第i个数变成k时，前i个数调整的代价和最小值。
    // 枚举第i-1个数调整成的数字j，再枚举第i个数调整成k.做转移。
    int MinAdjustmentCost(vector<int> &A, int target) {
        int n = A.size();
        vector<vector<int>> result(n + 1, vector<int>(101, INT_MAX));
        for (int i = 0; i < 101; ++i)
        {
            result[0][i] = 0;
        }
        for (int i = 1; i <= n; ++i)
        {
            for (int j = 1; j <= 100; ++j)
            {
                if (result[i - 1][j] != INT_MAX)
                for (int k = 1; k <= 100; ++k)
                {
                    if (abs(j - k) <= target)
                    {
                        result[i][k] = min(result[i][k], result[i - 1][j] + abs(A[i - 1] - k));
                    }
                }
            }
        }
        int ans = INT_MAX;
        for (int i = 1; i <= 100; ++i)
        {
            ans = min(ans, result[n][i]);
        }
        return ans;
    }
};